package com.feng.ioc.configuration;

import com.feng.ioc.bean.Red;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.StringValueResolver;

import javax.sql.DataSource;

@PropertySource("classpath:/db.properties")
@Configuration
public class ProfileConfig implements EmbeddedValueResolverAware {
//此处用多种方法为属性赋值赋值
    @Value("${db.user}")
    private  String user;

    private StringValueResolver  resolveStringValue;

    private String driver;

    //指定组件在哪个环境下生效
   @Profile("test")
    @Bean("test")
    public DataSource dataSourceTest(@Value("${db.password}") String password) throws Exception {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(password);
        String url = resolveStringValue.resolveStringValue("${db.url}");

        dataSource.setJdbcUrl(url);

        dataSource.setDriverClass(driver);
        return dataSource;
    }
    @Profile("dev")
    @Bean("dev")
    public DataSource dataSourceDev(@Value("${db.password}") String password) throws Exception {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(password);

        String url = resolveStringValue.resolveStringValue("${db.url}");
        dataSource.setJdbcUrl(url);

        dataSource.setDriverClass(driver);
        return dataSource;
    }

    @Profile("prod")
    @Bean("prod")
    public DataSource dataSourceProd(@Value("${db.password}") String password) throws Exception {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(password);

        String url = resolveStringValue.resolveStringValue("${db.url}");
        dataSource.setJdbcUrl(url);

        dataSource.setDriverClass(driver);
        return dataSource;
    }

    @Override
    public void setEmbeddedValueResolver(StringValueResolver resolver) {

        this.resolveStringValue=resolver;
        this.driver=resolver.resolveStringValue("${db.driver}");
        System.out.println(driver);

    }

    //默认是@Profile("default") 可以在任何环境下生效
    @Bean
    public Red red(){
        return  new Red();
    }
}
